<template>
  <el-upload
    class="t-upload"
    ref="upload"
    action=""
    :on-preview="handlePreview"
    :on-remove="handleRemove"
    :on-change="handleChange"
    :file-list="fileList"
    :auto-upload="false"
    :limit="1"
    :disabled="disabled"
    :accept="accept"
  >
    <el-button v-show="!disabled" slot="trigger" size="mini" type="primary"
      >选取文件</el-button
    >
  </el-upload>
</template>
<script>
export default {
  props: {
    value: {
      type: [Object, String],
      default: null,
      require: true,
    },
    disabled: {
      type: Boolean,
      default: false,
    },
    accept: {
      type: String,
      default: ""
    }
  },
  data() {
    return {};
  },
  computed: {
    fileList: {
      get() {
        if (typeof this.value == "string") {
          return [];
        }
        return this.value ? [this.value] : [];
      },
      set(val) {
        this.$emit("input", val?.length ? val[0] : null);
      },
    },
  },
  methods: {
    focus() {},
    submitUpload() {
      this.$refs.upload.submit();
    },
    handleChange(file, fileList) {
      const _this = this;
      fileList.forEach((ele) => {
        let reader = new FileReader(); // 创建文件读取对象
        reader.readAsDataURL(file.raw); // 文件读取装换为base64类型
        reader.onloadend = function (e) {
          let tmpObj = {
            id: null,
            content: this.result,
            name: file.name,
            type: "singleFile",
          };
          _this.fileList = [tmpObj];
          _this.$emit("change", file);
        };
      });
    },
    handleRemove(file, fileList) {
      this.fileList = [];
    },
    handlePreview(file) {
      this.$emit("file-click", file);
    },
  },
};
</script>
<style lang="scss" scoped>
::v-deep .el-upload {
  display: block;
  text-align: left;
}
</style>
